<?php

class Helper_Categories {
	
	private static $instance;
	
	public static function newInstance() {
		if (! self::$instance instanceof self) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	public function __construct() {
	
	}
	
	public function createSelect($cats, $level) {
		if (count ( $cats ) < 1) {
			throw new Exception ( 'Empty Cateogry Array' );
		}
		
		$html = array ();
		$html [] = '<select name="cat" class="level">';
		$html [] = '<option value="0">Select Subcategory</option>';
		foreach ( $cats as $cat ) {
			
			$html [] = '<option value="' . $cat ['category_id'] . '">' . $cat ['name'] . '</option>';
		
		}
		$html [] = '</select>';
		return implode ( '', $html );
	}
	
	public function createOption($prefix = '', $default_id = 0) {
		
		$top = Model_Mapper_Categories::newInstance ()->getTopCategories ( true, true );
		return $this->_createOption ( $top, $prefix, $default_id );
	}
	
	public function _createOption($top, $prefix = '&nbsp;&nbsp;', $default_id = 0) {
		$str = '';
		if ($prefix == '') {
			$prefix = '&nbsp;&nbsp;';
		}
		
		foreach ( $top as $item ) {
			
			if (Model_Mapper_Categories::newInstance ()->hasSubCateogries ( $item ['category_id'] )) {
				$str .= '<option disabled="disabled" style="background:#cccccc" value="' . $item ['category_id'] . '">' . $prefix . $item ['name'] . '</option>';
				$str .= $this->_createOption ( Model_Mapper_Categories::newInstance ()->getSubCategories ( $item ['category_id'],true ), $prefix . $prefix ,$default_id);
			} else {
				$selected = '';
				if ($item ['category_id'] == $default_id) {
					$selected = 'selected="selected"';
				} else {
					$selected = '';
				}
				
				$str .= '<option value="' . $item ['category_id'] . '" ' . $selected . '  >' . $prefix . $item ['name'] . '</option>';
			}
		}
		return $str;
	}
}